import modelExtend from 'dva-model-extend'
import { getList, update } from './services/config'
import { lwjPageModel } from 'utils/model'

export default modelExtend(lwjPageModel, {
  namespace: 'config',
  state: {
    items: [],
    currentItem: {},
    modalVisible: false
  },
  subscriptions: {
    setup ({dispatch, history}) {

    },
  },
  effects: {
    * onGetList ({payload}, {call, put}) {
      const {name} = payload
      if (typeof name === 'undefined') {
        throw new Error('没有输入搜索项')
      }

      const res = yield call(getList, {namespace: name})
      const {result} = res
      let array = []
      for (let prop in result) {
        if (result.hasOwnProperty(prop)) {
          array.push({
            id: prop,
            name: prop,
            configure: result[prop]
          })
        }
      }
      yield put({
        type: 'setItems',
        payload: array
      })
    },

    * onUpdate ({payload}, {call, put}) {
      const {name, configure} = payload
      const data = {[name]: configure}

      const res = yield call(update, data)
      if (! res.success) {
        throw new Error("修改失败")
      }
    }
  },
  reducers: {
    setItems (state, {payload}) {
      state.items = payload

      return {
        ...state
      }
    },

    setItem (state, {payload}) {
      state.currentItem = payload

      return {
        ...state
      }
    },

    openModal (state, {payload}) {
      state.modalVisible = true

      return {
        ...state
      }
    },

    /**
     * 隐藏所有modal
     * @param state
     * @param payload
     * @return {{}}
     */
    hideModal (state, {payload}) {
      state.modalVisible = false

      return {
        ...state
      }
    }
  },
})
